package com.runtime.hongyunuser.service.Impl;

import com.runtime.hongyunuser.bean.Carousels;
import com.runtime.hongyunuser.bean.Categories;
import com.runtime.hongyunuser.mapper.CategoriesMapper;
import com.runtime.hongyunuser.service.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CategoriesServiceImpl implements CategoriesService {

    @Autowired
    private CategoriesMapper categoriesMapper;


    @Override
    public List<Map<String, Object>> getCatalogData() {
        // 获取所有顶级分类并按sortOrder排序
        List<Categories> rootCategories = categoriesMapper.selectRootCategories()
                .stream()
                .sorted(Comparator.comparing(Categories::getSortOrder))
                .collect(Collectors.toList());

        // 构建目录数据结构
        return rootCategories.stream()
                .map(this::buildCatalogEntry)
                .collect(Collectors.toList());
    }

    @Override
    public List<Carousels> getAllActiveCarousels() {
        LocalDate now = LocalDate.now();
        return categoriesMapper.findAllActive(now.toString());
    }

    private Map<String, Object> buildCatalogEntry(Categories category) {
        Map<String, Object> entry = new HashMap<>();
        entry.put("title", category.getCategoryName());

        // 直接使用imageUrl，可能为null
        entry.put("image", category.getImageUrl());

        // 处理子分类
        List<Map<String, String>> products = categoriesMapper.selectChildCategories(category.getCategoryId())
                .stream()
                .sorted(Comparator.comparing(Categories::getSortOrder))
                .map(this::buildProductEntry)
                .collect(Collectors.toList());

        entry.put("products", products);
        return entry;
    }

    private Map<String, String> buildProductEntry(Categories subCategory) {
        Map<String, String> product = new HashMap<>();
        product.put("name", subCategory.getCategoryName());

        // 直接使用imageUrl，可能为null
        product.put("image", subCategory.getImageUrl());

        return product;
    }
}